﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

using Developmentalmadness.Web.UI.AjaxAbstractions;

namespace Developmentalmadness.Web.UI.ExtJsControlLibrary
{
    [ParseChildren(true)]
    public class ExtJsMenu : ExtJsObservable
    {
        private List<ConfigItem> _defaults = new List<ConfigItem>();
        private List<ExtJsObservable> _items = new List<ExtJsObservable>();
        private List<ScriptReference> _references = new List<ScriptReference>();

        /// <summary>
        /// Registeres script dependencies with the page
        /// </summary>
        /// <remarks>
        /// This is dependent upon GetScriptDescriptors() being called first.
        /// Otherwise, child dependencies found within the 'items' collection
        /// won't get registered. At the moment this doesn't seem to be a problem
        /// as the .NET Framework (as well as this one) follow this pattern.
        /// 
        /// The reason for this dependency is the 'items' collection. The objects
        /// in the collection aren't instantiated the same way as a control found
        /// in the page or body templates. An object in the collection has no
        /// reference to Page or ScriptManager and it's page events aren't called.
        /// I don't think this is a problem, since the 'items' collection are objects
        /// don't begin their life-cycle until the page is loaded anyway.
        /// </remarks>
        public override List<ScriptReference> GetScriptReferences()
        {
            _references.AddRange(base.GetScriptReferences());

            return _references;
        }

        public override IList<ScriptDescriptor> GetScriptDescriptors()
        {
            IList<ScriptDescriptor> list = base.GetScriptDescriptors();

            ScriptControlDescriptorBase desc = (ScriptControlDescriptorBase)list[0];

            desc.Type = "Ext.menu.Menu";

            String[] properties = new String[]{
                "allowOtherMenus", "defaultAlign", "minWidth", 
                "shadow", "subMenuAlign"
            };

            Type component = typeof(ExtJsMenu);

            foreach (String property in properties)
            {
                PropertyInfo i = component.GetProperty(property);

                if (i == null)
                    throw new InvalidOperationException(String.Format("Property not found, 'ExtJsMenu.{0}'", property));

                Object value = i.GetValue(this, null);

                if (value == null)
                    continue;

                if (!(value is String))
                    desc.AddPropertyBase(property, value);
                else
                    desc.AddPropertyBase(property, String.Format("'{0}'", value));
            }

            //add defaults
            if (defaults.Count != 0)
            {
                StringBuilder config = new StringBuilder("{");

                for (int i = 0; i < defaults.Count; i++)
                {
                    if (i != 0)
                    {
                        config.Append(",");
#if DEBUG
                        config.AppendLine();
#endif
                    }
                    config.AppendFormat("{0} : '{1}'", defaults[i].name, defaults[i].value);
                }

                config.Append("}");

#if DEBUG
                config.AppendLine();
#endif

                desc.AddPropertyBase("defaults", config);
            }

            //add items
            if (items.Count != 0)
            {
                // build items list
                StringBuilder itemList = new StringBuilder("[");

                for (int i = 0; i < items.Count; i++)
                {
                    if (!(items[i] is IMenuItem))
                        throw new InvalidOperationException("Controls in the 'items' property of ExtJsMenu must implement IMenuItem.");

                    // add comma between items
                    if (i != 0)
                    {
                        itemList.Append(",");
#if DEBUG
                        itemList.AppendLine("\t\t\t");
#endif
                    }

                    // get the item script
                    itemList.Append(((IMenuItem)items[i]).GetMenuItemScript());

                    // get the items's list of script dependencies
                    IEnumerable<ScriptReference> references = items[i].GetScriptReferences();
                    
                    // make sure the script dependencies are registered
                    _references.AddRange(references);
                }

                itemList.Append("]");

                desc.AddPropertyBase("items", itemList);
            }

            return list;
        }


        #region public properties

        public Boolean? allowOtherMenus { get; set; }

        public String defaultAlign { get; set; }

        [NotifyParentProperty(true)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<ConfigItem> defaults
        {
            get
            {
                return _defaults;
            }
        }

        [NotifyParentProperty(true)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public List<ExtJsObservable> items
        {
            get
            {
                return _items;
            }
        }

        public Int32? minWidth { get; set; }

        public shadow? shadow { get; set; }

        public String subMenuAlign { get; set; }

        #endregion
    }

    
}
